package com.ss.web.tagmark.utils;

import java.lang.reflect.Method;
import java.util.Date;

import javax.persistence.Entity;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ss.web.tagmark.init.SecurityWebAuthenticationDetails;

public class ReflectUtils {
	/**
	 * 将orig中非null的属性值复制到dest对应的属性中
	 *
	 * @param orig
	 * @param dest
	 */
	public static void copyNotNullProperties(Object orig, Object dest) {
		if (orig == null || dest == null) {
			return;
		}
		for (Class<?> cl = orig.getClass(); cl != Object.class; cl = cl.getSuperclass()) {
			Method[] ms = cl.getDeclaredMethods();
			if (ms != null && ms.length > 0) {
				for (Method m : ms) {
					String name = m.getName();
					if (!name.startsWith("get")) {//获取get方法
						continue;
					}
					try {
						Object value = m.invoke(orig);
						if (value == null) {
							continue;
						}
						String propertyName = name.substring(3);
						propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);

						BeanUtils.copyProperty(dest, propertyName, value);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 自动设置添加信息
	 *
	 * @param entity
	 */
	public static void addAddInfo(Object entity) {
		if (entity == null || entity.getClass().getAnnotation(Entity.class) == null) {
			return;
		}
		String curUserId = "0";
		String curIp = "127.0.0.1";
		try {
			if (SecurityContextHolder.getContext().getAuthentication() != null) {
				SecurityWebAuthenticationDetails details = (SecurityWebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
				curIp = details.getRealIp();
			}
		} catch (Exception e) {
		}
		setProperty(entity, "adderId", curUserId);
		setProperty(entity, "adderTime", new Date());
		setProperty(entity, "adderIp", curIp);
	}

	/**
	 * 自动设置修改信息
	 *
	 * @param entity
	 */
	public static void addModifyInfo(Object entity) {
		if (entity == null || entity.getClass().getAnnotation(Entity.class) == null) {
			return;
		}
		String curUserId = "0";
		String curIp = "127.0.0.1";
		try {
			if (SecurityContextHolder.getContext().getAuthentication() != null) {
				SecurityWebAuthenticationDetails details = (SecurityWebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
				curIp = details.getRealIp();
			}
		} catch (Exception e) {
		}
		setProperty(entity, "updaterId", curUserId);
		setProperty(entity, "updaterTime", new Date());
		setProperty(entity, "updaterIp", curIp);
	}

	/**
	 * 往对象中设置值，不报错
	 *
	 * @param arg
	 * @param name
	 * @param value
	 */
	public static void setProperty(Object arg, String name, Object value) {
		try {
			BeanUtils.setProperty(arg, name, value);
		} catch (Exception e) {
		}
	}
}
